import React from 'react';
import storage from '../../util/Storage';
import md5 from 'js-md5';
import {connect}           from 'react-redux';
import { 
    Input,
    Icon,
    Form, 
    Button,
    message}  from 'antd';
import  {
    getVerification,
    sendRes,
    sendEmail}              from "../../redux/action/common/userhead";
import './Register.less';
const FormItem  =Form.Item;
let   timeReg=null;
let   timeNum=59;
@connect(state=>({
    header:state.userHeader
})
)
/**
 * 注册页面
 */
class Register extends React.Component {
constructor(props) {
    super(props);

    this.state = {
        isregButton:false,
        isemailform:false,
        time:59,
        istime:true

    };
}
componentDidMount(){
    this.getCaptcha();
}
/**
 * 获取图片验证码
 */
getCaptcha=()=>{
    this.props.dispatch(
        getVerification())
        .then(()=>{
            if(this.props.header.Captcha!=undefined)
            {
                this.setState({
                    picSource :this.props.header.Captcha.data.code,
                    uuid      :this.props.header.Captcha.data.uuid
                })
            }
            else
            {
                message.warning("验证码获取失败");
            }
    })
}

     // 检查注册
    checkPass(rule, value, callback) {
        const { validateFields } = this.props.form;
        if (value) {
            validateFields(['passwords'], {
                force: true,
            });
        }
        callback();
    }

    checkPass2(rule, value, callback) {
        const { getFieldValue } = this.props.form;
        if (value && value !== getFieldValue('password')) {
            callback('两次输入密码不一致！');
        } else {
            callback();
        }
    }
    /**
     * button和验证码部分变换
     */
    handleChange=()=>{
        this.setState({
            isregButton:!this.state.isregButton,
            isemailform:!this.state.isemailform
        })
       
    }
    /**
     * 接收邮箱验证码，开始倒计时
     */
    handleStartTime=()=>{
        let apply=this.props.form.getFieldsValue();
        storage.setStorage('validation',apply.validation);
        this.handleChange();
       
        clearInterval(timeReg);
        timeReg=setInterval(() => {
            this.setState({
                time:timeNum
            })
            timeNum-=1;
            if(timeNum==0)
            {
                this.setState({
                    istime:false
                })
                clearInterval(timeReg);
            }
        }, 1000);
    }

    /**
     * 向邮箱发送验证码
     */
    sendEmailid=()=>{    
        let apply=this.props.form.getFieldsValue();
        if(apply.email!='')
        {
            this.handleStartTime();
            this.props.dispatch(
                sendEmail(apply.email))
                .then(()=>{})
        }
        else{
            message.warning('邮箱不能为空');
        }  
    }
   
    /**
     * 注册
     */
    toRegister=()=>{
        let apply=this.props.form.getFieldsValue();//获取表单信息
        if(this.props.header.emailKey.data      ===''
         &&apply.password                       ===''
         &&this.props.header.Captcha.data.uuid  ===''
         &&apply.email                          ===''
         &&apply.emailvalidation                ===''
         &&localStorage.validation              ==='')
        {
            message.warning('信息不能为空')
        }
        else
        {
            //切换到最开始的注册页面
            this.handleChange();
            this.getCaptcha();
            // 添加固定盐
            let salt ="1a2b3c4d";
            let str = ""+salt.charAt(0)+salt.charAt(2) 
            + apply.password+salt.charAt(5) + salt.charAt(4); 
            console.log('str',str);
            let passw=md5(str);
            this.props.dispatch(sendRes({
                password    :passw,
                email       :apply.email,
                emailUuid   :this.props.header.emailKey.data,
                emailCode   :apply.emailvalidation,
                verifyUuid  :this.props.header.Captcha.data.uuid,
                verifyCode  :localStorage.validation
            }))
        }
    }

    closeWindow=()=>{
        window.location.href='/';
    }


    render() {
        const {isregButton,picSource,isemailform,time,istime}=this.state;
        const {getFieldDecorator}=this.props.form;
        const styleImg={ 
            cursor  :'pointer',
            width   :100,
            height  :30,
            paddingBottom:5
        }
        return (
            <div className="register-wrap">
                <div className="register-content">
                    <div className="register-header">
                        <div style={{width:"80%",float:"left",paddingLeft:"60px"}}>欢迎注册</div>
                        <div onClick={this.closeWindow} style={{float:"right",paddingRight:"10px"}}><Icon type="close" /></div>
                        
                    </div>
                    <div className="register-form">
                        <Form style={{width:350}}>
                        <FormItem>
                                    {
                                        getFieldDecorator('email',{
                                            initialValue:'',
                                            rules:[{
                                                pattern:new RegExp('^[a-z0-9A-Z]+[- | a-z0-9A-Z . _]+@([a-z0-9A-Z]+(-[a-z0-9A-Z]+)?\\.)+[a-z]{2,}$'),
                                                message:'请填写正确的邮箱格式'
                                            }]
                                        })( <Input prefix={<Icon type="mail" />} placeholder="请填写邮箱"/>)
                                    }
                        </FormItem>
                                {
                                    isemailform?
                                    <> 
                                <FormItem>
                                    {
                                        getFieldDecorator('emailvalidation',{
                                            initialValue:'',
                                            rules:[]
                                        })( <Input 
                                            prefix={<Icon type="heart" />} 
                                            style={{width:200,float:'left'}} 
                                            placeholder="请输邮箱验证码"/>)

                                    }
                                    {
                                        istime? <div style={{float:'right',marginRight:30,border:'1px solid #eee'} }>
                                            {time}后重新
                                            </div>: 
                                            <div onClick={this.handleChange} 
                                            style={{float:'right',marginRight:30,border:'1px solid #eee'}}>
                                                重新发送
                                            </div>
                                    }
                                   
                                </FormItem></>
                                :<><FormItem>
                                    {
                                        getFieldDecorator('validation',{
                                            initialValue:'',
                                            rules:[]
                                        })( <Input 
                                            prefix={<Icon type="heart" />}
                                            style={{width:200,float:'left'}} 
                                            placeholder="请输入验证码"/>)

                                    }
                                    <div style={{float:'right',marginRight:30} }>
                                        <img 
                                            src={picSource?`data:image/png;base64,${picSource}`:null} 
                                            style={styleImg}
                                            onClick={()=>this.getCaptcha()}
                                        />
                                        </div>
                                </FormItem>
                                </>

                                }
                                <FormItem>
                                    {
                                        getFieldDecorator('password',{
                                            initialValue:'',
                                            rules:[{
                                                pattern:new RegExp('^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{6,20}$'),
                                                message:'密码至少包含 数字和英文，长度6-20'
                                            },
                                            {
                                                 validator:this.checkPass.bind(this),
                                            },]
                                        })( <Input.Password prefix={<Icon type="lock"/>} placeholder="请输入密码"/>)
                                    }
                                </FormItem>
                                <FormItem>
                                    {
                                        getFieldDecorator('passwords',{
                                            initialValue:'',
                                            rules:[{
                                                validator: this.checkPass2.bind(this),
                                            },
                                            {
                                                pattern:new RegExp('^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{6,20}$'),
                                                message:'密码至少包含 数字和英文，长度6-20'
                                            },
                                        ]
                                        })( <Input.Password 
                                            prefix={<Icon type="lock"/>} 
                                            placeholder="请确认密码"/>)
                                    }
                                </FormItem>
                                {
                                    isregButton?<Button 
                                                style={{width:300,marginLeft:25,backgroundColor:"#5A50A2",borderColor:"#5A50A2"}} 
                                                onClick={this.toRegister}  
                                                type="primary">
                                        注册
                                        </Button> :
                                    <Button 
                                    style={{width:300,marginLeft:25,backgroundColor:"#5A50A2",borderColor:"#5A50A2"}} 
                                    onClick={this.sendEmailid}   
                                    type="primary">
                                        发送验证码
                                    </Button>
                                }
                        
                        </Form>
                        <div></div>
                    </div>

                </div>
            </div>
        );
    }
}



export default Form.create()(Register);